<template>
    <div class="table-wrap">
        <download :formData="formData" :columns="objColumns" :allColumns="allColumns"></download>
        <dataColumSetting
            ref="dataColum"
            :columns="columns"
            :allColumns="allColumns"
            w="615px"
            @updColumns="updColumn"
            size="small"
        ></dataColumSetting>
        <accoun></accoun>
        <div class="navControl">
            <el-switch v-model="showLine" :active-text="$t('m.label.displayChart')" size="small"></el-switch>
            <ul v-show="showLine">
                <li>
                    <el-radio
                        v-model="businessReport"
                        label="findBusinessReport"
                        @change="businessReports"
                        size="mini"
                    >{{$t('m.label.day')}}</el-radio>
                </li>
                <li>
                    <el-radio
                        v-model="businessReport"
                        label="findByWeek"
                        @change="businessReports"
                    >{{$t('m.label.week')}}</el-radio>
                </li>
                <li>
                    <el-radio
                        v-model="businessReport"
                        label="findByMonth"
                        @change="businessReports"
                    >{{$t('m.label.month')}}</el-radio>
                </li>
            </ul>
        </div>
        <div class="line" v-show="showLine" v-if="!loading">
            <v-line :lineData="tableData" v-if="lineloading"></v-line>
        </div>
        <el-table
            ref="table"
            :data="tableData.concat(summary).concat(total)"
            border
            style="width: 100%"
            v-loading="loading"
            :header-cell-style="getRowClass"
            :style="!showLine?'margin-top: 10px':''"
        >
            <el-table-column
                key="1"
                prop="recordDate"
                :label="$t('m.label.date')"
                v-if="!objColumns.recordDate"
            >
                <template slot-scope="scope">
                    {{scope.row.recordDate}}
                    <span
                        class="formatDay"
                        v-if="scope.row.recordDate != '日均' &&  scope.row.recordDate != '汇总' && businessReport === 'findBusinessReport'"
                    >({{scope.row.recordDate | formatDay}})</span>
                    <span
                        v-if="scope.row.recordDate != '周均' &&  scope.row.recordDate != '汇总' && businessReport === 'findByWeek'"
                    >({{$t('m.label.week')}})</span>
                    <span
                        v-if="scope.row.recordDate != '月均' &&  scope.row.recordDate != '汇总' && businessReport === 'findByMonth'"
                    >({{$t('m.label.month')}})</span>
                </template>
            </el-table-column>
            <el-table-column
                key="2"
                prop="sessions"
                :label="$t('m.label.flow')"
                v-if="!objColumns.sessions"
            ></el-table-column>
            <el-table-column
                key="3"
                prop="sessionPercentage"
                :label="$t('m.label.flow')+'(%)'"
                v-if="!objColumns.sessionPercentage"
            >
                <template
                    slot-scope="scope"
                >{{scope.row.sessionPercentage}}{{scope.row.sessionPercentage || scope.row.sessionPercentage ===0?'%':''}}</template>
            </el-table-column>
            <el-table-column
                key="4"
                prop="pageViews"
                :label="$t('m.label.pageviews')"
                v-if="!objColumns.pageViews"
            ></el-table-column>
            <el-table-column
                key="5"
                prop="pageViewsPercentage"
                :label="$t('m.label.pageviews')+'(%)'"
                v-if="!objColumns.pageViewsPercentage"
            >
                <template
                    slot-scope="scope"
                >{{scope.row.pageViewsPercentage}}{{scope.row.pageViewsPercentage || scope.row.pageViewsPercentage ===0?'%':''}}</template>
            </el-table-column>
            <el-table-column
                key="6"
                prop="buyBoxPercentage"
                :label="$t('m.label.shoppingCart')+'(%)'"
                v-if="!objColumns.buyBoxPercentage"
            >
                <template
                    slot-scope="scope"
                >{{scope.row.buyBoxPercentage}}{{scope.row.buyBoxPercentage || scope.row.buyBoxPercentage ===0?'%':''}}</template>
            </el-table-column>
            <el-table-column
                key="7"
                prop="unitSessionPercentage"
                :label="$t('m.label.conversionRates') + '(%)'"
                v-if="!objColumns.unitSessionPercentage"
            >
                <template
                    slot-scope="scope"
                >{{scope.row.unitSessionPercentage | numFilter}}{{scope.row.unitSessionPercentage || scope.row.unitSessionPercentage ===0?'%':''}}</template>
            </el-table-column>
            <el-table-column
                key="8"
                prop="totalOrderItems"
                :label="$t('m.label.orderQuantity')"
                v-if="!objColumns.totalOrderItems"
            ></el-table-column>
            <el-table-column
                key="9"
                prop="unitsOrdered"
                :label="$t('m.label.salesVolume')"
                v-if="!objColumns.unitsOrdered"
            ></el-table-column>
            <el-table-column
                key="10"
                prop="orderedProductSales"
                :label="$t('m.label.orderedProductSales') +' (￥)'"
                v-if="!objColumns.orderedProductSales"
            >
                <template
                    slot-scope="scope"
                >{{scope.row.orderedProductSales || scope.row.orderedProductSales ===0?'￥':''}}{{scope.row.orderedProductSales | numFilter}}</template>
            </el-table-column>
            <el-table-column
                key="11"
                prop="priceAvg"
                :label="$t('m.label.priceAvg') + '(￥)'"
                v-if="!objColumns.priceAvg"
            >
                <template
                    slot-scope="scope"
                >{{scope.row.priceAvg || scope.row.priceAvg ===0?'￥':''}}{{scope.row.priceAvg}}</template>
            </el-table-column>
        </el-table>
        <scrollTable ref="scrollTable"></scrollTable>
    </div>
</template>
<script>
const ERR_OK = 200;
import { formatDate } from "assets/js/date";
import scrollTable from "components/scroll/scroll-table.vue";
import accoun from "./accoun.vue";
let vm = {};
export default {
    props: ["formData"],
    data() {
        vm = this;
        return {
            loading: true,
            lineloading: false,
            businessReport: "findBusinessReport",
            tableData: [],
            dayData: [],
            weekData: [],
            monthData: [],
            summary: [],
            total: [],
            showLine: true,
            objColumns: {},
            columns: [],
            allColumns: []
        };
    },
    filters: {
        formatDay(time) {
            return vm.$t("m.label.weekTime").charAt(new Date(time).getDay());
        },
        numFilter(value) {
            // 截取当前数据到小数点后两位
            let realVal = parseFloat(value).toFixed(2);
            return realVal;
        }
    },
    mounted() {
        this.allColumns = JSON.parse(JSON.stringify(this.$refs.table.columns));
        // this.businessReports();
    },
    methods: {
        // 标题背景颜色
        getRowClass({ row, column, rowIndex, columnIndex }) {
            if (rowIndex === 0) {
                return "background: #EBEEF5 ";
            } else {
                return "";
            }
        },
        // 按天周月查询businessReport数据
        businessReports() {
            if (
                this.dayData.length > 0 &&
                this.businessReport === "findBusinessReport"
            ) {
                this.tableData = this.dayData;
            } else if (
                this.weekData.length > 0 &&
                this.businessReport === "findByWeek"
            ) {
                this.tableData = this.weekData;
            } else if (
                this.monthData.length > 0 &&
                this.businessReport === "findByMonth"
            ) {
                this.tableData = this.monthData;
            } else {
                this.loading = true;
                let data = [];
                let businessReportId = "";
                if (this.businessReport === "findBusinessReport") {
                    businessReportId =
                        "/" + this.$store.getters.userId;
                }
                let formData = JSON.parse(JSON.stringify(this.formData));
                delete formData.date;
                this.lineloading = false;
                this.$ajax({
                    method: "post",
                    url:
                        this.GLOBAL.businessReportService +
                        "/business/" +
                        this.businessReport +
                        businessReportId,
                    data: formData
                }).then(res => {
                    this.loading = false;
                    if (res.data.data) {
                        data = res.data.data;
                        this._arrSortTimeData(data.datas);
                        this._arrData(data);
                        this.total = data.汇总;
                        this.total.recordDate = "汇总";
                        if (data.dataCloumn) {
                            this.getColumn(JSON.parse(data.dataCloumn));
                        }
                    } else {
                        this.total = [];
                        this.summary = [];
                        this.tableData = [];
                    }
                    this.$refs.scrollTable.scrollShow(this.$refs.table);
                });
            }
        },
        // 过滤时间
        _arrSortTimeData(data) {
            let tableData = [];
            for (let i in data) {
                for (let e in data[i]) {
                    if (
                        (e === "sessionPercentage" ||
                            e === "pageViewsPercentage" ||
                            e === "buyBoxPercentage" ||
                            e === "unitSessionPercentage" ||
                            e === "orderedProductSales" ||
                            e === "priceAvg") &&
                        data[i][e]
                    ) {
                        data[i][e] = data[i][e].toFixed(2);
                    }
                }
                if (this.businessReport === "findBusinessReport") {
                    let date = new Date(data[i].recordDate);
                    data[i].recordDate = formatDate(date, "yyyy-MM-dd");
                    tableData.push(data[i]);
                } else {
                    tableData.push(data[i]);
                }
            }
            if (this.businessReport === "findBusinessReport") {
                this.dayData = tableData;
                this.clockData(tableData);
            } else if (this.businessReport === "findByWeek") {
                this.weekData = tableData;
                this.clockData(tableData);
            } else {
                this.monthData = tableData;
                this.clockData(tableData);
            }
        },
        clockData(data) {
            let clock = setInterval(() => {
                this.tableData = data;
                this.lineloading = true;
                clearInterval(clock);
            }, 200);
        },
        // 添加日均
        _arrData(data) {
            let item = "";
            if (data.日均) {
                item = data.日均;
                item.recordDate = "日均";
            } else if (data.周均) {
                item = data.周均;
                item.recordDate = "周均";
            } else {
                item = data.月均;
                item.recordDate = "月均";
            }
            if (item.orderedProductSales) {
                item.orderedProductSales = item.orderedProductSales.toFixed(2);
            }
            if (item.buyBoxPercentage) {
                item.buyBoxPercentage = item.buyBoxPercentage.toFixed(2);
            }
            if (item.unitSessionPercentage) {
                item.unitSessionPercentage = item.unitSessionPercentage.toFixed(
                    2
                );
            }
            if (item.totalOrderItems) {
                item.totalOrderItems = item.totalOrderItems.toFixed(0);
            }
            if (item.priceAvg) {
                item.priceAvg = item.priceAvg.toFixed(2);
            }
            this.summary = item;
        },
        // 标题背景颜色
        getRowClass({ row, column, rowIndex, columnIndex }) {
            if (rowIndex === 0) {
                return "background: #EBEEF5 ";
            } else {
                return "";
            }
        },
        getColumn(val) {
            this.objColumns = {};
            this.columns = val;
            this.allColumns.forEach(ele => {
                if (val.indexOf(ele.property) === -1) {
                    this.objColumns[ele.property] = true;
                }
            });
        },
        // 更新数据列
        updColumn(val) {
            this.$ajax({
                method: "post",
                url:
                    this.GLOBAL.businessReportService +
                    "/dataColumn/updateUserDataColumn?dataColumn=" +
                    val.join() +
                    "&userId=" +
                    this.$store.getters.userId
            }).then(res => {
                if (res.data.code === ERR_OK) {
                    this.getColumn(val);
                    this.$refs.dataColum.dataColumhide();
                } else {
                    this.$message.error(res.data.msg);
                }
            });
        }
    },
    watch: {
        formData() {
            this.dayData = [];
            this.weekData = [];
            this.monthData = [];
            this.businessReport = "findBusinessReport";
            this.businessReports();
        }
    },
    components: {
        scrollTable,
        accoun,
        "v-line": resolve => require(["./charts.vue"], resolve),
        download: resolve => require(["./download.vue"], resolve),
        dataColumSetting: resolve =>
            require([
                "components/dataColumSetting/dataColumSetting.vue"
            ], resolve)
    }
};
</script>
<style lang="stylus" scoped>
.table-wrap {
    .el-table--border {
    }

    .line {
        padding: 0 10px;
    }

    .navControl {
        padding: 10px 0 0 10px;

        ul {
            display: inline-block;
            margin-left: 10px;

            li {
                display: inline-block;
                margin-right: 5px;
            }
        }
    }

    .formatDay {
        margin-left: 5px;
    }
}
</style>
<style lang="stylus">
.navControl {
    span.el-switch__core {
        width: 34px !important;
        height: 16px;

        &:after {
            margin-left: -14px !important;
            width: 12px;
            height: 12px;
        }
    }

    .el-radio__inner {
        width: 12px;
        height: 12px;
    }

    .el-radio__label {
        padding-left: 3px;
    }
}
</style>

